package com.fqgj.sentry.handler;

import com.fqgj.common.api.ApiResponse;
import com.fqgj.common.api.enums.BasicErrorCodeEnum;


import com.fqgj.sentry.common.exception.BizException;
import com.fqgj.sentry.common.exception.enums.ErrorCodeEnums;
import com.fqgj.log.interfaces.Log;
import com.fqgj.log.factory.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * USER: cainaitao
 * Date: 2017/4/13
 * Time: 13:55
 */

@ControllerAdvice
public class ApiExceptionHandler {

    private static final Log LOGGER = LogFactory.getLog(ApiExceptionHandler.class);


    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        ApiResponse response = new ApiResponse(BasicErrorCodeEnum.PARAM_VALID_ERROR);
        BindingResult result = e.getBindingResult();
        StringBuffer sb = new StringBuffer();
        for (FieldError error : result.getFieldErrors()) {
            String field = error.getField();
            String code = error.getDefaultMessage();
            String message = String.format("%s:%s", field, code);
            sb.append(message);
        }
        response.setMsg(sb.toString());
        return response;
    }

    /**
     * get请求参数的验证
     *
     * @return
     */
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ApiResponse errorResponse(MissingServletRequestParameterException e) {
        LOGGER.warn("异常信息为：{}", e);
        return new ApiResponse(BasicErrorCodeEnum.PARAM_RESOLVE_ERROR.getCode(), "参数解析异常");
    }


    @ExceptionHandler(value = BizException.class)
    @ResponseStatus(value = HttpStatus.OK)
    @ResponseBody
    public ApiResponse applicationErrorHandler(BizException e){
        LOGGER.warn("异常信息为：{}", e);
        return new ApiResponse(e.getErrorId(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.OK)
    @ResponseBody
    public ApiResponse errorException(Exception e) {
        LOGGER.warn("异常信息为：{}", e);
        return new ApiResponse(ErrorCodeEnums.unknow_error);
    }
}